<template>
  <div class="paren">
    <Explanation 
      v-if="showExplan" 
      :ModelData="selectedModel"
      @back="handleBack"
      @status-updated="handleStatusUpdated"
    />
    <template v-else>
       <div class="table-wrapper">
        <el-table
          :data="tableData"
          height="100%"
          :header-cell-style="{ color: 'rgb(82,85,96)' }"
        >
          <el-table-column prop="model" label="Model" show-overflow-tooltip></el-table-column>
          <el-table-column prop="dealer" label="Dealer" show-overflow-tooltip></el-table-column>
          <el-table-column label="Image">
            <template #default="scope">
              <div v-if="scope.row.image">
                <img 
                  :src="scope.row.image" 
                  style="width: 80px; height: 60px; object-fit: contain;"
                />
              </div>
              <span v-else>No Image</span>
            </template>
          </el-table-column>
          <el-table-column label="Details" show-overflow-tooltip>
            <template #default="scope">
              <el-button @click="showExplanation(scope.row)">Modify</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加按钮 -->
      <div class="add-button-container">
        <el-button 
          type="primary" 
          @click="handleAdd"
          class="add-button"
        >
          Add
        </el-button>
      </div>

      <!-- 添加对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%" class="large-dialog">
        <el-form :model="formData" label-width="80px">
          <el-form-item label="Model" prop="model" :rules="[{ required: true, message: 'Please select the model', trigger: 'change' }]">
            <el-select
              v-model="formData.model"
              placeholder="Please select the model"
              filterable
              clearable
              @change="checkModelUnique"
              size='large'
            >
              <el-option
                v-for="item in Models"
                :key="item.id"
                :lable="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="Dealer" required>
            <el-input v-model="formData.dealer" :disabled="true"></el-input>
          </el-form-item>
            <p style="font-size: 16px;margin-top: 30px;color: orange;">(Tip: Please enter the details page to edit the description content.)</p>

        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false" class="footer-button">Cancel</el-button>
            <el-button type="primary" @click="handleConfirm" class="footer-button">confirm</el-button>
          </span>
        </template>
      </el-dialog>
    </template> 
  </div>
</template>

<script setup>
  import { ref,onMounted, computed } from 'vue';
  import axios from 'axios';
  import { ElMessage } from 'element-plus';
  import Explanation from '../details/Explanation.vue';
  import { useManageStore } from '../../store/manageStore';
  import { useLoading } from '../../utils/loading';
  const manageStore = useManageStore()
  const { showLoading,hideLoading } = useLoading()
  const BASE_URL = import.meta.env.VITE_API_URL

  const dealer = computed(() => manageStore.dealer)
  const tableData = ref([]);
  const dialogVisible = ref(false);
  const dialogTitle = ref('添加数据');

  const showExplan = ref(false);
  const selectedModel = ref(null);
  

  const Models = ref([]);
  const formData = ref({
    title: '',
    content: '',
    videoUrl: '',
    imgUrl: '',
    dealer: dealer.value,
    model: ''
  })

  onMounted (() => {
    getModelList(),
    fetchData()
  })
  const getModelList = async() => {
    try {
      showLoading('Loading models...')
      const res = await axios.get(`${BASE_URL}manage/modelList`,{
        params: {
          dealer:dealer.value
        }
      })
      
      if(res.data.code === 0 && Array.isArray(res.data.data)) {
        Models.value = res.data.data.map((modelName, index) => ({
          id: index.toString(), // 使用数组索引作为 id
          label: modelName      // 直接使用返回的文本作为 label
        }));
      }
    }catch(error) {
      ElMessage.error(error.msg)
    } finally {
      hideLoading()
    }
  }
  const fetchData = async() => {
    try {
      showLoading('Loading data...')
      const res = await axios.get(`${BASE_URL}manage/introductionsByDealer`,{
        params: {
          dealer: dealer.value
        }
      })
      let resultData = res.data;
      if(resultData.code === 0){
        tableData.value = resultData.data
      }else {
        ElMessage.error(resultData.msg)
      }
    }catch(error) {
      ElMessage.error(error.msg)
    } finally {
      hideLoading();
    }
  }

  const handleAdd = () => {
    dialogTitle.value = 'Add data';
    dialogVisible.value = true;
  }
  //限制model重复
  const checkModelUnique = () => {
    const exists = tableData.value.some(item => item.model === formData.value.model);
    if(exists) {
      ElMessage.warning('This model already exists. Please make modifications in the details of this model to prevent the original content from being overwritten.')
      formData.value.model = '';
    }
  }

  const handleConfirm = async() => {
    if(!formData.value.model) {
      ElMessage.warning('Please select a model');
      return;
    }
    try{
      showLoading('Submitting data...')
      const res = await axios.post(`${BASE_URL}manage/addIntroduction`,formData.value)
      tableData.value.push({ ...formData.value });
      ElMessage.success('Added successfully');
      dialogVisible.value = false;
      await fetchData();
    }catch(error) {
      ElMessage.error('Operation failed: ' + error.msg);
    }finally {
      hideLoading();
    }
  }

  //跳转修改内容
  function showExplanation(row) {
    selectedModel.value = row;
    showExplan.value = true;
  }
  const handleBack = async()=> {
    showExplan.value = false;
    await fetchData(); // 重新获取数据
  }
  //获取此行内容状态
  function handleStatusUpdated({id,state}){
    // 更新tableData中对应的记录
    const index = tableData.value.findIndex(item => item.id === id);
    if (index !== -1 ){
      tableData.value[index].state = state;
    }
    // 如果当前正在查看的就是这条记录，也更新selectedModel
    if (selectedModel.value && selectedModel.value.id === id){
      selectedModel.value.state = state;
    }
  }
</script>

<style scoped>
  .paren {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 180px);
    width: 100%;
    box-sizing: border-box;
    background-color: white;
    color: black;
  }
  .add-button-container {
    flex-shrink: 0;
    padding: 18px 50px 18px 100px;
    display: flex;
    justify-content: flex-end;
  }
  :deep(.add-button) {
    font-size: 20px;
    width: 80px;
    height: 40px;
    border-radius: 10px;
  }
  .table-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    margin-bottom: 10px;
  }
  /* 固定表头样式 */
  :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
  }
  /* 表格滚动区域 */
  :deep(.el-table__body-wrapper) {
    overflow-y: auto;
    flex: 1;
  }
  /* 表格全局居中样式 */
  :deep(.el-table .el-table__cell) {
    text-align: center;
    height: 80px;
    font-size: 20px;
  }
  :deep(.el-table .el-table__cell .cell) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  :deep(.el-table .el-button) {
    font-size: 18px;
    width: 80px;
    height: 35px;
    border-radius: 8px;
  }

  :deep(.large-dialog) {
    font-size: 20px; /* 增大对话框内所有文字的字体大小 */
    min-height: 35%;
    position: relative;
  }
  :deep(.large-dialog .el-form-item__label),
  :deep(.large-dialog .el-input__inner) {
    height: 40px !important;
    font-size: 18px !important;
    line-height: 40px !important;
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    position: absolute;
    right: 20px;
    bottom: 20px;
  }
  /* 底部按钮样式 */
  :deep(.large-dialog .footer-button) {
    font-size: 18px;
    padding: 12px 24px;
    height: 38px;
    width: 80px;
    margin-left: 20px;
  }
</style>